package com.crm.service.system.impl;

import cn.hutool.core.util.ObjectUtil;

import com.crm.context.BaseContext;
import com.crm.dto.RolePageDTO;
import com.crm.exception.BaseException;
import com.crm.mapper.system.RoleMapper;
import com.crm.pojo.Role;
import com.crm.result.PageResult;
import com.crm.result.Result;
import com.crm.service.system.RoleService;
import com.crm.utils.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;


    @Override
    public PageResult list(RolePageDTO rolePageDTO) {
        rolePageDTO.check();

        PageHelper.startPage(rolePageDTO.getPageNum(), rolePageDTO.getPageSize());

        Map<String, Object> params = rolePageDTO.getParams();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate beginTime = ObjectUtil.isEmpty(params) ? null : (LocalDate.parse((String) params.get("beginTime"), formatter));
        LocalDate endTime = ObjectUtil.isEmpty(params) ? null : (LocalDate.parse((String) params.get("endTime"), formatter));

        rolePageDTO.setBeginTime(beginTime);
        rolePageDTO.setEndTime(endTime);

        Page<Role> page = roleMapper.list(rolePageDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Role getByRoleId(Long id) {
        return roleMapper.getByRoleId(id);
    }

    @Override
    public void deletById(List<Long> ids) {
        roleMapper.deleteById(ids);
    }

    @Override
    public void add(Role role) {
        role.setCreateBy(String.valueOf(BaseContext.getCurrentId()));
        role.setUpdateBy(String.valueOf(BaseContext.getCurrentId()));
        role.setDataScope("1");
        role.setDelFlag("0");
        roleMapper.add(role);
    }

    @Override
    public void changeStatus(Role role) {
        role.setUpdateBy(String.valueOf(BaseContext.getCurrentId()));
        roleMapper.changeStatus(role);
    }

    @Override
    public void update(Role role) {
        role.setUpdateBy(String.valueOf(BaseContext.getCurrentId()));
        roleMapper.update(role);
    }

}
